package com.yunkazaixian.syntelecom.utils;

import com.alibaba.fastjson.JSONObject;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class ClientHandler extends SimpleChannelInboundHandler<String> {

    private final Logger log = LoggerFactory.getLogger(ClientHandler.class);
    private NettyClient nettyClient;

    public ClientHandler(NettyClient nettyClient) {
        this.nettyClient = nettyClient;
    }

    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.error("服务端连接成功!");
    }


    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {

        //收到服务端发来的心跳消息，给出回应

        if ("HEARTBEAT".equals(msg)) {

            ctx.writeAndFlush("ALIVE$$");

        } else {

            //msg是获取到服务端返回的消息，判断是否上报成功，如果不成功，可以将消息保存起来，重新发送
            System.out.println(JSONObject.parseObject(msg));

        }

    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        NettyClient.channel = null;
        log.error("服务端掉线了---");
        nettyClient.connect();//重连服务器
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}